<?php

class Core_Backend_Component_Website_Controller_Template extends Dcmp_Component_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function indexAction($pageindex = 1, $pagesize = 20, $sort='id', $dir='asc', $areaid = 0) {
        $this->getHistory()->record();
        $areas = App::getHelper('global')->getAreas();
        if (!$areaid) {
            $areaid = $areas->getFirstItem()->getId();
        }
        $collection = App::getModel('website/collection_template')
                        ->sortBy($sort, $dir)
                        ->joinArea()
                        ->filterByArea($areaid)
                        ->pagination($pageindex, $pagesize)
                        ->load();
        $records = $collection->loadCount();
        return $this->viewResult(array('list' => $collection, 'records' => $records, 'areas' => $areas, 'current_area_id' => $areaid));
    }

    public function createAction($areaid) {
        $area = App::getModel('global/area')->load($areaid);
        return $this->viewResult(array('area' => $area));
    }

    public function editAction($id) {
        $model = App::getModel('website/template')->load($id);
        return $this->createAction($model->getAreaId())->setModel($model);
    }

    public function applyPostAction() {
        return $this->savePostAction(FALSE);
    }

    public function savePostAction() {
        return $this->saveModel();
    }

    private function saveModel($return = TRUE) {
        $data = $this->getRequest()->getForm('template');
        $model = App::getModel('website/template');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }
        $model->addData($data)->setCreatorId(Kd_Web::getIdentity()->getId());
        if (($errors = $model->validate()) === TRUE) {
            $model->save();
            $this->getMessager()->addInform($this->__f('global.message.saveSuccess', '{global.label.domain}', $model->getName()));
            return $this->getRequest()->getForm('apply', FALSE) ?
                    $this->redirectResult($this->getUrl(array('id' => $model->getIdValue()), 'edit')) :
                    $this->redirectResult($this->getHistoryUrl('website/template/index'));
        } else {
            $this->getMessager()->addError($this->__f('global.message.saveFail', '{global.label.domain}', $model->getName()))
                    ->addError($errors);
            return $this->viewResult(array('model' => $model));
        }
    }

}

